﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Common;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CardInChina.Web.Mvc.Models;

namespace CardInChina.Web.Mvc.Controllers
{
    public class DeployController : Controller
    {
        //
        // GET: /Deploy/

        public ActionResult Install()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Install(SecureHeader model)
        {
            if (ModelState.IsValid && model.Code == "User@123")
            {
                try
                {
                    var schema = new string[] { 
                        System.IO.File.ReadAllText(Server.MapPath("~/data/cic-00.sql")),
                        System.IO.File.ReadAllText(Server.MapPath("~/data/cic-01.sql")),
                        System.IO.File.ReadAllText(Server.MapPath("~/data/cic-02.sql")),
                    };

                    // install
                    using (var cn = DbProviderFactories.GetFactory("MySql.Data.MySqlClient").CreateConnection())
                    {
                        cn.ConnectionString = ConfigurationManager.ConnectionStrings["CicInstall"].ConnectionString;
                        cn.Open();

                        var cmd = cn.CreateCommand();

                        foreach (var sql in schema)
                        {
                            cmd.CommandText = sql;
                            cmd.ExecuteNonQuery();
                        }

                        cn.Close();
                    }

                    return RedirectToAction("Index", "Home");
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", e.Message);
                }
            }
            else
            {
                ModelState.AddModelError("", "Model state is invalid or code is not correct!");
            }

            return View(model);
        }
    }
}

namespace CardInChina.Web.Mvc.Models
{
    public class SecureHeader
    {
        public string Code { get; set; }
    }
}

